package nix.anim.service.impl;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import nix.anim.common.pojo.NixResult;
import nix.anim.mapper.RoleMapper;
import nix.anim.mapper.UserMapper;
import nix.anim.mapper.UserRoleMapper;
import nix.anim.pojo.Role;
import nix.anim.pojo.User;
import nix.anim.pojo.UserRole;
import nix.anim.pojo.UserRoleExample;
import nix.anim.service.UserRoleService;

/**
 * 用户角色关系管理Service
 */
@Service
public class UserRoleServiceImpl implements UserRoleService {

	@Autowired
	private UserRoleMapper userRoleMapper;
	
	@Autowired
	private UserMapper userMapper;
	
	@Autowired
	private RoleMapper roleMapper;
	
	@Override
	public NixResult deleteAll() {
		// 删除全部
		userRoleMapper.deleteByExample(new UserRoleExample());
		return NixResult.ok();
	}

	@Override
	public NixResult addUserRole(Integer userId, Integer roleId) {
		// 验证用户是否存在
		User user = userMapper.selectByPrimaryKey(userId);
		if (user == null) {
			return NixResult.build(400, "关联的用户不存在！");
		}
		// 验证角色是否存在
		Role role = roleMapper.selectByPrimaryKey(roleId);
		if (role == null) {
			return NixResult.build(400, "关联的角色不存在！");
		}
		// 补全属性
		UserRole userRole = new UserRole();
		userRole.setUserId(userId);
		userRole.setRoleId(roleId);
		userRole.setCreated(new Date());
		userRole.setUpdated(new Date());
		// 插入数据
		userRoleMapper.insert(userRole);
		return NixResult.ok();
	}

}
